<template>
  <div class="property-company-detail">
    <!-- 页面头部 -->
    <el-card class="header-card" shadow="never">
      <div class="header-content">
        <div class="company-info">
          <div class="company-logo" v-if="companyDetail.companyLogo">
            <img :src="companyDetail.companyLogo" alt="公司Logo" />
          </div>
          <div class="company-basic">
            <h2>{{ companyDetail.companyName }}</h2>
            <p class="company-code">编码：{{ companyDetail.companyCode }}</p>
            <div class="status-tags">
              <el-tag :type="companyDetail.status === 1 ? 'success' : 'danger'">
                {{ companyDetail.status === 1 ? '启用' : '禁用' }}
              </el-tag>
              <el-tag :type="getAuditStatusType(companyDetail.auditStatus)">
                {{ getAuditStatusText(companyDetail.auditStatus) }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="warning" @click="handleAudit" v-if="companyDetail.auditStatus === 0">
            <el-icon><Check /></el-icon>
            审核
          </el-button>
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 详细信息 -->
    <el-row :gutter="20" class="detail-content">
      <!-- 基本信息 -->
      <el-col :span="16">
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="公司名称">
              {{ companyDetail.companyName }}
            </el-descriptions-item>
            <el-descriptions-item label="公司编码">
              {{ companyDetail.companyCode }}
            </el-descriptions-item>
            <el-descriptions-item label="统一社会信用代码">
              {{ companyDetail.creditCode || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="营业执照号">
              {{ companyDetail.businessLicense || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="法定代表人">
              {{ companyDetail.legalRepresentative || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="联系人">
              {{ companyDetail.contactPerson }}
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">
              {{ companyDetail.contactPhone }}
            </el-descriptions-item>
            <el-descriptions-item label="联系邮箱">
              {{ companyDetail.contactEmail || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱地址">
              {{ companyDetail.email || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="成立日期">
              {{ companyDetail.establishedDate || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="注册资本">
              {{ companyDetail.registeredCapital ? `${companyDetail.registeredCapital}万元` : '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="资质等级">
              {{ companyDetail.qualificationLevel || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="服务热线">
              {{ companyDetail.serviceHotline || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="营业时间" span="2">
              {{ companyDetail.businessHours || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="公司地址" span="2">
              {{ companyDetail.address || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="服务范围" span="2">
              {{ companyDetail.serviceScope || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="公司简介" span="2">
              {{ companyDetail.introduction || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="公司描述" span="2">
              {{ companyDetail.description || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="公司状态" span="2">
              <el-tag :type="companyDetail.status === 1 ? 'success' : 'danger'">
                {{ companyDetail.status === 1 ? '正常' : '停用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="审核状态" span="2">
              <el-tag :type="getAuditStatusType(companyDetail.auditStatus)">
                {{ getAuditStatusText(companyDetail.auditStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="审核备注" span="2" v-if="companyDetail.auditRemark">
              {{ companyDetail.auditRemark }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 用户列表 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>用户列表</span>
              <div class="header-actions">
                <el-button type="primary" size="small" @click="handleAddUser">
                  <el-icon><Plus /></el-icon>
                  新增用户
                </el-button>
              </div>
            </div>
          </template>
          
          <el-table
            v-loading="userLoading"
            :data="userList"
            style="width: 100%"
          >
            <el-table-column label="用户名" prop="username" width="120" />
            <el-table-column label="真实姓名" prop="realName" width="120" />
            <el-table-column label="手机号" prop="phone" width="130" />
            <el-table-column label="用户类型" prop="userType" width="120">
              <template #default="{ row }">
                <el-tag :type="getUserTypeTagType(row.userType)">
                  {{ getUserTypeText(row.userType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                  {{ row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center" fixed="right">
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  link 
                  @click="handleEnableUser(row)" 
                  v-if="row.status === 0"
                >
                  启用
                </el-button>
                <el-button 
                  type="warning" 
                  link 
                  @click="handleDisableUser(row)" 
                  v-if="row.status === 1"
                >
                  禁用
                </el-button>
                <el-button 
                  type="info" 
                  link 
                  @click="handleResetPassword(row)"
                >
                  重置密码
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-model:current-page="userQueryParams.current"
            v-model:page-size="userQueryParams.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="userTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleUserSizeChange"
            @current-change="handleUserCurrentChange"
            style="margin-top: 20px; justify-content: flex-end"
          />
        </el-card>

        <!-- 支付信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>支付信息</span>
            </div>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="收款账户">
              {{ companyDetail.paymentAccount || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="开户银行">
              {{ companyDetail.paymentBank || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="微信支付商户号">
              {{ companyDetail.wechatPayMerchantId || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="支付宝商户号">
              {{ companyDetail.alipayMerchantId || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="在线支付链接" span="2">
              {{ companyDetail.paymentLink || '-' }}
            </el-descriptions-item>
          </el-descriptions>

          <!-- 收款二维码 -->
          <div v-if="companyDetail.paymentQrCode" class="qr-code-section">
            <h4>收款二维码</h4>
            <div class="qr-code-container">
              <img :src="companyDetail.paymentQrCode" alt="收款二维码" />
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 侧边栏 -->
      <el-col :span="8">
        <!-- 统计信息 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>统计信息</span>
            </div>
          </template>
          
          <div class="stats-list">
            <div class="stat-item">
              <div class="stat-label">关联社区数</div>
              <div class="stat-value">{{ stats.communityCount || 0 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">员工数量</div>
              <div class="stat-value">{{ stats.employeeCount || 0 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">服务房户数</div>
              <div class="stat-value">{{ stats.householdCount || 0 }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">本月收入</div>
              <div class="stat-value">¥{{ stats.monthlyIncome || 0 }}</div>
            </div>
          </div>
        </el-card>

        <!-- 操作记录 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>操作记录</span>
            </div>
          </template>
          
          <div class="operation-list">
            <div class="operation-item" v-for="record in operationRecords" :key="record.id">
              <div class="operation-time">{{ formatDateTime(record.createTime) }}</div>
              <div class="operation-content">{{ record.operation }}</div>
              <div class="operation-user">{{ record.operator }}</div>
            </div>
            <div v-if="operationRecords.length === 0" class="empty-text">
              暂无操作记录
            </div>
          </div>
        </el-card>

        <!-- 审核记录 -->
        <el-card class="detail-card" shadow="never" v-if="auditRecords.length > 0">
          <template #header>
            <div class="card-header">
              <span>审核记录</span>
            </div>
          </template>
          
          <div class="audit-list">
            <div class="audit-item" v-for="record in auditRecords" :key="record.id">
              <div class="audit-header">
                <span class="audit-status" :class="getAuditStatusClass(record.auditStatus)">
                  {{ getAuditStatusText(record.auditStatus) }}
                </span>
                <span class="audit-time">{{ formatDateTime(record.createTime) }}</span>
              </div>
              <div class="audit-content">{{ record.auditRemark || '无备注' }}</div>
              <div class="audit-user">审核人：{{ record.auditor }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑对话框 -->
    <PropertyCompanyForm
      ref="formRef"
      :visible="formVisible"
      :form-data="formData"
      :is-edit="true"
      @success="handleFormSuccess"
      @cancel="handleFormCancel"
    />

    <!-- 审核对话框 -->
    <PropertyCompanyAudit
      ref="auditRef"
      :visible="auditVisible"
      :company-id="companyId"
      @success="handleAuditSuccess"
      @cancel="handleAuditCancel"
    />
  </div>
</template>

<script setup lang="ts">
/**
 * 物业公司详情页面
 * @author Wu.Liang
 * @date 2025-01-29
 */

import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Check, Back, Plus } from '@element-plus/icons-vue'
import propertyCompanyApi from '@/api/property/propertyCompany'
import type { PropertyCompany, PropertyCompanyFormData } from '../types/property'
import PropertyCompanyForm from './components/PropertyCompanyForm.vue'
import PropertyCompanyAudit from './components/PropertyCompanyAudit.vue'
import { formatDateTime } from '@/utils'
import { showError, showSuccess, showWarning } from '@/utils/message'

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const companyId = ref<number>(0)
const companyDetail = ref<PropertyCompany>({} as PropertyCompany)
const formRef = ref()
const auditRef = ref()

// 表单相关
const formVisible = ref(false)
const formData = ref<PropertyCompanyFormData>({})

// 审核相关
const auditVisible = ref(false)

// 统计数据
const stats = reactive({
  communityCount: 0,
  employeeCount: 0,
  householdCount: 0,
  monthlyIncome: 0
})

// 操作记录
const operationRecords = ref<any[]>([])

// 审核记录
const auditRecords = ref<any[]>([])

// 用户列表相关
const userLoading = ref(false)
const userList = ref<any[]>([])
const userTotal = ref(0)
const userQueryParams = reactive({
  current: 1,
  size: 10
})

// 生命周期
onMounted(() => {
  const id = route.params.id
  if (id) {
    companyId.value = Number(id)
    getCompanyDetail()
    getCompanyStats()
    getOperationRecords()
    getAuditRecords()
    getUserList()
  }
})

// 获取公司详情
const getCompanyDetail = async () => {
  try {
    loading.value = true
    const response = await propertyCompanyApi.getPropertyCompanyDetail(companyId.value)
    if (response.code === 200) {
      companyDetail.value = response.data
    } else {
      showError(response.message || '获取公司详情失败')
    }
  } catch (error) {
    console.error('获取公司详情失败:', error)
    showError('获取公司详情失败')
  } finally {
    loading.value = false
  }
}

// 获取公司统计信息
const getCompanyStats = async () => {
  try {
    // 获取基础统计信息
    const response = await propertyCompanyApi.getPropertyCompanyDetailStats(companyId.value)
    if (response.code === 200) {
      Object.assign(stats, response.data)
    }
    
    // 获取员工数量（从用户列表API的total字段获取）
    try {
      const userResponse = await propertyCompanyApi.getPropertyCompanyUsers(companyId.value, { current: 1, size: 1 })
      if (userResponse.code === 200) {
        stats.employeeCount = userResponse.data.total || 0
      }
    } catch (error) {
      console.error('获取员工数量失败:', error)
      stats.employeeCount = 0
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 获取操作记录
const getOperationRecords = async () => {
  // 这里应该调用获取操作记录的API
  // 暂时使用模拟数据
  operationRecords.value = [
    {
      id: 1,
      operation: '更新公司信息',
      operator: '管理员',
      createTime: new Date().toISOString()
    },
    {
      id: 2,
      operation: '新增公司',
      operator: '系统',
      createTime: new Date(Date.now() - 86400000).toISOString()
    }
  ]
}

// 获取审核记录
const getAuditRecords = async () => {
  // 这里应该调用获取审核记录的API
  // 暂时使用模拟数据
  auditRecords.value = [
    {
      id: 1,
      auditStatus: 1,
      auditRemark: '审核通过，资质齐全',
      auditor: '审核员',
      createTime: new Date().toISOString()
    }
  ]
}

// 编辑
const handleEdit = () => {
  formData.value = {
    companyName: companyDetail.value.companyName || '',
    companyCode: companyDetail.value.companyCode || '',
    contactPerson: companyDetail.value.contactPerson || '',
    contactPhone: companyDetail.value.contactPhone || '',
    businessLicense: companyDetail.value.businessLicense,
    legalRepresentative: companyDetail.value.legalRepresentative,
    contactEmail: companyDetail.value.contactEmail,
    address: companyDetail.value.address,
    establishedDate: companyDetail.value.establishedDate,
    registeredCapital: companyDetail.value.registeredCapital,
    serviceScope: companyDetail.value.serviceScope,
    qualificationLevel: companyDetail.value.qualificationLevel,
    paymentQrCode: companyDetail.value.paymentQrCode,
    paymentAccount: companyDetail.value.paymentAccount,
    paymentBank: companyDetail.value.paymentBank,
    paymentLink: companyDetail.value.paymentLink,
    wechatPayMerchantId: companyDetail.value.wechatPayMerchantId,
    alipayMerchantId: companyDetail.value.alipayMerchantId,
    companyLogo: companyDetail.value.companyLogo,
    introduction: companyDetail.value.introduction,
    businessHours: companyDetail.value.businessHours,
    serviceHotline: companyDetail.value.serviceHotline
  } as PropertyCompanyFormData
  formVisible.value = true
}

// 审核
const handleAudit = () => {
  auditVisible.value = true
}

// 返回
const handleBack = () => {
  router.back()
}

// 表单成功回调
const handleFormSuccess = () => {
  formVisible.value = false
  getCompanyDetail()
}

// 表单取消回调
const handleFormCancel = () => {
  formVisible.value = false
}

// 审核成功回调
const handleAuditSuccess = () => {
  auditVisible.value = false
  getCompanyDetail()
  getAuditRecords()
}

// 审核取消回调
const handleAuditCancel = () => {
  auditVisible.value = false
}

// 获取审核状态类型
const getAuditStatusType = (status: number) => {
  switch (status) {
    case 0: return 'warning'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}

// 获取审核状态文本
const getAuditStatusText = (status: number) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '审核通过'
    case 2: return '审核拒绝'
    default: return '未知'
  }
}

// 获取审核状态样式类
const getAuditStatusClass = (status: number) => {
  switch (status) {
    case 0: return 'status-pending'
    case 1: return 'status-approved'
    case 2: return 'status-rejected'
    default: return 'status-unknown'
  }
}

// 获取用户列表
const getUserList = async () => {
  try {
    userLoading.value = true
    const response = await propertyCompanyApi.getPropertyCompanyUsers(companyId.value, userQueryParams)
    if (response.code === 200) {
      userList.value = response.data.records || []
      userTotal.value = response.data.total || 0
    } else {
      showError(response.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    showError('获取用户列表失败')
  } finally {
    userLoading.value = false
  }
}

// 新增用户
const handleAddUser = () => {
  router.push(`/property/company/add-user/${companyId.value}`)
}

// 启用用户
const handleEnableUser = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要启用用户"${row.username}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await propertyCompanyApi.enableUser(row.id)
    if (response.code === 200) {
      showSuccess('启用成功')
      getUserList()
    } else {
      showError(response.message || '启用失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('启用用户失败:', error)
      showError('启用失败')
    }
  }
}

// 禁用用户
const handleDisableUser = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要禁用用户"${row.username}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await propertyCompanyApi.disableUser(row.id)
    if (response.code === 200) {
      showSuccess('禁用成功')
      getUserList()
    } else {
      showError(response.message || '禁用失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('禁用用户失败:', error)
      showError('禁用失败')
    }
  }
}

// 重置密码
const handleResetPassword = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要重置用户"${row.username}"的密码吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await propertyCompanyApi.resetUserPassword(row.id)
    if (response.code === 200) {
      showSuccess('密码重置成功')
    } else {
      showError(response.message || '密码重置失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
      showError('重置密码失败')
    }
  }
}

// 用户分页大小变化
const handleUserSizeChange = (size: number) => {
  userQueryParams.size = size
  userQueryParams.current = 1
  getUserList()
}

// 用户当前页变化
const handleUserCurrentChange = (current: number) => {
  userQueryParams.current = current
  getUserList()
}

// 获取用户类型标签类型
const getUserTypeTagType = (userType: string) => {
  switch (userType) {
    case 'COMMUNITY_ADMIN': return 'success'
    case 'PROPERTY_STAFF': return 'primary'
    case 'SECURITY_STAFF': return 'warning'
    case 'REPAIR_STAFF': return 'info'
    case 'RESIDENT': return 'default'
    case 'PROPERTY_ADMIN': return 'danger'
    case 'BUILDING_ADMIN': return 'success'
    case 'UNIT_ADMIN': return 'primary'
    case 'HOUSEHOLD_ADMIN': return 'warning'
    case 'NORMAL_USER': return 'default'
    default: return 'info'
  }
}

// 获取用户类型文本
const getUserTypeText = (userType: string) => {
  switch (userType) {
    case 'COMMUNITY_ADMIN': return '社区管理员'
    case 'PROPERTY_STAFF': return '物业人员'
    case 'SECURITY_STAFF': return '安保人员'
    case 'REPAIR_STAFF': return '维修人员'
    case 'RESIDENT': return '居民'
    case 'PROPERTY_ADMIN': return '物业管理员'
    case 'BUILDING_ADMIN': return '楼栋管理员'
    case 'UNIT_ADMIN': return '单元管理员'
    case 'HOUSEHOLD_ADMIN': return '房户管理员'
    case 'NORMAL_USER': return '普通用户'
    default: return '未知'
  }
}
</script>

<style lang="scss" scoped>
.property-company-detail {
  padding: 20px;
  
  .header-card {
    margin-bottom: 20px;
    
    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .company-info {
        display: flex;
        align-items: center;
        gap: 20px;
        
        .company-logo {
          img {
            width: 80px;
            height: 80px;
            border-radius: 8px;
            border: 1px solid #dcdfe6;
          }
        }
        
        .company-basic {
          h2 {
            margin: 0 0 8px 0;
            color: #303133;
          }
          
          .company-code {
            margin: 0 0 12px 0;
            color: #909399;
            font-size: 14px;
          }
          
          .status-tags {
            display: flex;
            gap: 8px;
          }
        }
      }
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .detail-content {
    .detail-card {
      margin-bottom: 20px;
      
      .card-header {
        font-weight: 600;
        color: #303133;
      }
    }
    
    .qr-code-section {
      margin-top: 20px;
      
      h4 {
        margin: 0 0 12px 0;
        color: #303133;
      }
      
      .qr-code-container {
        text-align: center;
        
        img {
          width: 150px;
          height: 150px;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
        }
      }
    }
    
    .stats-list {
      .stat-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .stat-label {
          color: #606266;
          font-size: 14px;
        }
        
        .stat-value {
          color: #303133;
          font-weight: 600;
          font-size: 16px;
        }
      }
    }
    
    .operation-list {
      .operation-item {
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .operation-time {
          color: #909399;
          font-size: 12px;
          margin-bottom: 4px;
        }
        
        .operation-content {
          color: #303133;
          font-size: 14px;
          margin-bottom: 4px;
        }
        
        .operation-user {
          color: #606266;
          font-size: 12px;
        }
      }
      
      .empty-text {
        text-align: center;
        color: #909399;
        padding: 20px 0;
      }
    }
    
    .audit-list {
      .audit-item {
        padding: 12px 0;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .audit-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
          
          .audit-status {
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
            color: white;
            
            &.status-pending {
              background-color: #e6a23c;
            }
            
            &.status-approved {
              background-color: #67c23a;
            }
            
            &.status-rejected {
              background-color: #f56c6c;
            }
            
            &.status-unknown {
              background-color: #909399;
            }
          }
          
          .audit-time {
            color: #909399;
            font-size: 12px;
          }
        }
        
        .audit-content {
          color: #303133;
          font-size: 14px;
          margin-bottom: 4px;
        }
        
        .audit-user {
          color: #606266;
          font-size: 12px;
        }
      }
    }
  }
}
</style> 